package com.cya.cyaproducts;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.cya.entities.Product;

public class LibJsonParse {

	public static ArrayList<Item> getListProducts(String result) {
		ArrayList<Item> list = null;
		try {
			if (result != null) {
				
				JSONObject o = new JSONObject(result);

				
				String result_success = o.getString("status");
				if (!result_success.equals("success")){
					return null;
				}
				
				JSONArray jArrayData = o.getJSONArray("data");
				
				list = new ArrayList<Item>();
				for (int j = 0; j < jArrayData.length(); j++) {
					JSONObject obj = jArrayData.getJSONObject(j);
					Item one_product = new Item(Integer.parseInt(
								obj.getString("item_id").toString()),
								obj.getString("item_name").toString(),
								obj.getString("item_short_desc").toString(),
								obj.getString("item_icon").toString(),
								obj.getString("item_like").toString(),
								obj.getString("item_download").toString(),
								obj.getString("item_download_fact").toString()
							);
					list.add(one_product);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		return list;
	}
	
	
	public static Product getProduct(String result) {
		Product one_product = new Product();
		try {
			if (result != null) {
				
				JSONObject o = new JSONObject(result);

				
				String result_success = o.getString("status");
				if (!result_success.equals("success")){
					return null;
				}
				
				JSONObject obj = o.getJSONObject("data");
				
				one_product.setId(Integer.parseInt(obj.getString("item_id").toString()));
				one_product.setName(obj.getString("item_name").toString());
				one_product.setIconFile(obj.getString("item_icon").toString());
				one_product.setDesc(obj.getString("item_short_desc").toString());
				
				String str=obj.getString("info").toString();
				JSONObject o1 = new JSONObject(str);
				one_product.setContent(o1.getString("info_desc").toString());
				
				ArrayList<String> image_product = new ArrayList<String>();

				JSONArray images_jsonArray = obj.getJSONArray("images");
				
				for (int i = 0; i< images_jsonArray.length(); i++) {
					JSONObject obj_temp = images_jsonArray.getJSONObject(i);
					image_product.add(obj_temp.getString("img_url").toString());
				}
				
				one_product.setArrayImage(image_product);
				
				
				one_product.setAmountLike(obj.getString("item_like").toString());
				one_product.setAmountDownload(obj.getString("item_download").toString());
				one_product.setAmountComment(obj.getString("item_download_fact").toString());
				
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		return one_product;
	}
}
